<template>
  <div class="upload-imgs">
    <!-- 
     -->
    <!-- 
      :limit="limit"
      :on-exceed="onExceed"
    {{ fileList }}
      :file-list="fileList"
     -->
    <el-upload
      class="upload-tag"
      ref="uploadRef"
      multiple
      :action="action"
      :accept="accept"
      :show-file-list="false"
      :disabled="uploadDisabled"
      :data="uploadData"
      :headers="headers"
      :before-upload="beforeUpload"
      :on-success="onSuccess"
      :on-error="onError"
    >
      <div class="upload-btn">
        <i class="el-icon-plus avatar-uploader-icon"></i>
      </div>
    </el-upload>
    <div v-if="isShow" class="render-img-box">
      <div
        class="file-item-box"
        v-for="(item, index) in fileList"
        :key="item.picUrl + index"
        @click="(e) => handleImg(e, item, index)"
      >
        <!-- {{ item.picUrl }} -->
        <el-image
          :lazy="true"
          :src="item.picUrl"
          :preview-src-list="[item.picUrl]"
        >
          <div slot="placeholder" class="image-slot">
            加载中<span class="dot">...</span>
          </div>
        </el-image>
      </div>
    </div>
  </div>
</template>

<script>
import { uploadUrl } from "@/api/public";
import loadingGif from "@/assets/loading.gif";
import { getToken } from "@/utils/auth";

export default {
  name: "upload-imgs",
  props: {
    isShow: {
      type: Boolean,
      default: true,
      required: false,
    },
    limit: {
      type: Number,
      default: 100,
      required: false,
    },
    renderList: {
      type: Array,
      default: () => {
        return [];
      },
      required: false,
    },
  },
  data() {
    return {
      action: uploadUrl,
      accept: ".jpg, .jpge, .png",
      fileList: [],
      uploadDisabled: false,
      headers: {
        Authorization: getToken(),
      },
      uploadData: {
        name: "",
      },
    };
  },
  watch: {
    renderList: {
      immediate: true,
      handler(val) {
        this.fileList = [...val];
      },
    },
  },
  created() {
    this.fileList = [...this.renderList];
  },
  methods: {
    handleImg(e, item, index) {
      const { target } = e;
      const { className } = target;
      console.log(className);
      if (className === "el-image") {
        const { name, id, picUrl } = this.fileList[index];
        console.log(this.fileList);
        console.log(picUrl);
        const getIndex = this.fileList.findIndex((el) => el.picUrl === picUrl);
        console.log(getIndex);
        this.fileList.splice(getIndex, 1);
        console.log(this.fileList);
        this.$emit("uploadOnChange", this.fileList);
      } else {
        console.log("preview");
      }
    },
    beforeUpload(file) {
      return new Promise(async (resolve, reject) => {
        const { name, type, lastModified } = file;
        // const { png, jpg, jpeg } = MIME_MAP;
        // if (type !== png && type !== jpg && type !== jpeg) {
        //   setTimeout(() => {
        //     this.$message.error(`【${name}】文件类型错误！`);
        //   }, 10);
        //   reject(file);
        //   return;
        // }
        this.uploadData.name = name;
        // const { prefixStr, suffix } = strByLastSymbolSlice(name, ".");
        // const splicName = `${prefixStr}_${new Date().getTime()}${suffix}`;
        // const imgFile = new File([file], splicName, {
        //   type,
        //   lastModified,
        // });
        if (this.fileList.length >= this.limit) {
          this.onExceed();
          reject(file);
          return;
        }
        try {
          resolve(file);
        } catch (err) {
          this.$message.error("图片加载出错，请重新选择图片");
          reject(file);
        }
      });
    },
    onExceed() {
      this.$message.error(`允许上传照片上限为${this.limit}张！`);
    },
    onSuccess(res, file, fileList) {
      console.log(res, file, fileList);
      // fileList.map((item) => {
      // const { picUrl } = item;
      // if (!picUrl) {
      //   item.picUrl = loadingGif;
      //   this.fileList.push(item);
      //   this.$emit("uploadOnChange", this.fileList);
      // }
      const { result, data } = res;
      if (result === 0 && data) {
        if (this.fileList.length >= this.limit) {
          this.onExceed();
          return;
        }
        const { picUrl } = data;
        this.fileList.push({
          ...file,
          picUrl,
        });
        // const sameIndex = this.fileList.findIndex((el) => {
        //   const { response } = el;
        //   if (response) {
        //     return picUrl === response.data.picUrl;
        //   }
        // });
        // if (sameIndex > -1) {
        //   const addItem = {
        //     ...this.fileList[sameIndex],
        //     picUrl,
        //   };
        //   this.fileList.splice(sameIndex, 1, addItem);
        this.$emit("uploadOnChange", this.fileList);
      }
      console.log(this.fileList);
      // } else {
      //   // 上传失败，移除imgdata数据
      //   const sameIndex = this.fileList.findIndex((el) => {
      //     const { name } = el;
      //     return name === file.name;
      //   });
      //   this.fileList.splice(sameIndex, 1);
      //   this.$emit("uploadOnChange", this.fileList);
      // }
      // });
    },
    onError() {
      this.$message.error("上传失败！");
    },
  },
};
</script>
<style scoped lang="scss">
.upload-imgs {
  display: flex;
  flex-wrap: wrap;
  > div {
    margin-right: 10px;
  }
  .render-img-box {
    display: flex;
    > div {
      margin-right: 10px;
    }
  }
  ::v-deep.upload-tag,
  .file-item-box {
    .el-upload,
    .el-image {
      width: 60px;
      height: 60px;
      line-height: 60px;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      font-size: 20px;
      overflow: inherit;

      .image-slot {
        width: 100%;
        height: 100%;
        font-size: 14px !important;
        text-align: center;
      }
    }

    .el-image {
      &:before {
        content: "x";
        position: absolute;
        top: -4px;
        right: -8px;
        color: #fff;
        background: #000;
        border-radius: 50%;
        width: 20px;
        height: 20px;
        text-align: center;
        line-height: 18px;
        display: none;
        font-size: 16px;
      }

      &:hover {
        border-color: #409eff;
        &:before {
          display: block;
          cursor: pointer;
        }
      }
    }
  }
}
</style>
